package com.itmake.sample.async.manager;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 异步任务管理器
 *
 * @author Amjacks
 * @since 2023/08/10
 */
public class AsyncManager {
    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;

    /**
     * @TODO 补充 获取 bean SpringUtil.getBean("scheduledExecutorService")
     * 异步操作任务调度线程池
     */
    private ScheduledExecutorService executor = null;

    /**
     * 单例模式
     */
    private AsyncManager() {
    }

    private static AsyncManager me = new AsyncManager();

    public static AsyncManager me() {
        return me;
    }

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void execute(TimerTask task) {
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止线程池
     * 先使用 shutdown, 停止接收新任务并尝试完成所有已存在任务.
     * 如果超时, 则调用 shutdownNow, 取消在 workQueue 中 Pending 的任务,并中断所有阻塞函数.
     * 如果仍然超時，則強制退出.
     * 另对在 shutdown 时线程本身被调用中断做了处理.
     */
    public void shutdown() {
        if (executor != null && !executor.isShutdown()) {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(120, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                    if (!executor.awaitTermination(120, TimeUnit.SECONDS)) {
                        // logger.info("Pool did not terminate");
                    }
                }
            } catch (InterruptedException ie) {
                executor.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
}
